package iorder

import org.springframework.dao.DataIntegrityViolationException
import ie.com.stamply.security.User
import grails.plugins.springsecurity.Secured
import services.ie.com.stamply.geo.GeoCoder


class CustomerController {
    
    def springSecurityService
    def burningImageService 
    def photoService;

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def index() {
        redirect(action: "list", params: params)
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [customerInstanceList: Customer.list(params), customerInstanceTotal: Customer.count()]
    }

    def create() {
        def user = User.get(springSecurityService.principal.id) 
        def customer = Customer.findByUser(user)
        if (customer.equals(null))
            [customerInstance: new Customer(params)]
        else redirect(action: "edit", id: customer.id)      
    }

    def save() {
        def customerInstance = new Customer(address: new Address(params))
        customerInstance.properties = params
        customerInstance = setNewCustomer(customerInstance)
        GeoCoder geoCoder = new GeoCoder();
        geoCoder.fillInLatLng(customerInstance.address)                      
        def uploadedFile = request.getFile('payload')
        photoService.photo = uploadedFile;
        println "Class: ${uploadedFile.class}"
        println "Name: ${uploadedFile.name}"
        println "OriginalFileName: ${uploadedFile.originalFilename}"
        println "Size: ${uploadedFile.size}"
        println "ContentType: ${uploadedFile.contentType}"        
        photoService.createImage(false,customerInstance.user.username,servletContext.getRealPath("/") )
       /*if(!uploadedFile.empty){
           println "Class: ${uploadedFile.class}"
           println "Name: ${uploadedFile.name}"
           println "OriginalFileName: ${uploadedFile.originalFilename}"
           println "Size: ${uploadedFile.size}"
           println "ContentType: ${uploadedFile.contentType}"
           def webRootDir = servletContext.getRealPath("/")
           def userDir = new File(webRootDir, "/images/customers/${customerInstance.user.username}/profile")
           userDir.mkdirs()
          // uploadedFile.transferTo( new File( userDir, uploadedFile.originalFilename))
           println "Path: ${userDir.getPath()}"
           burningImageService.doWith(uploadedFile, userDir.getPath())
                   .execute {
                       it.scaleApproximate(800, 600)
                    }
                   .execute ('tiny', {
                       it.scaleAccurate(25, 25)
                    })   
                   .execute ('topbar', {
                       it.scaleAccurate(16, 16)
                    }) 
                   .execute ('small', {
                       it.scaleAccurate(40, 40)
                    }) 
                   .execute ('medium', {
                       it.scaleAccurate(100, 100)
                    }) 
                
                   .execute ('master', {
                       it.scaleAccurate(378, 331)
                    }) 
                
                   .execute ('large', {
                       it.scaleAccurate(200, 200)
                    })         
            customerInstance.photoUrl = userDir.getPath();      
       }
      */
         customerInstance.photoUrl = 'userDir.getPath();'    
       
       
        if (!customerInstance.save(flush: true)) {
            render(view: "create", model: [customerInstance: customerInstance])
            return
        }

	flash.message = message(code: 'default.created.message', args: [message(code: 'customer.label', default: 'Customer'), customerInstance.id])
        redirect(action: "show", id: customerInstance.id)
    }
    
    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def show() {
        def customerInstance = Customer.get(params.id)
        if (!customerInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'customer.label', default: 'Customer'), params.id])
            redirect(action: "list")
            return
        }

        [customerInstance: customerInstance]
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def edit() {        
        def customerInstance = Customer.get(params.id)
        if (!customerInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'customer.label', default: 'Customer'), params.id])
            redirect(action: "list")
            return
        }

        [customerInstance: customerInstance]
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def update() {
        def customerInstance = Customer.get(params.id)        
        /*def currentDate = new Date()
        customerInstance..setLastUpdate(currentDate) */
        if (!customerInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'customer.label', default: 'Customer'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (customerInstance.version > version) {
                customerInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'customer.label', default: 'Customer')] as Object[],
                          "Another user has updated this Customer while you were editing")
                render(view: "edit", model: [customerInstance: customerInstance])
                return
            }
        }

        customerInstance.properties = params

        if (!customerInstance.save(flush: true)) {
            render(view: "edit", model: [customerInstance: customerInstance])
            return
        }

		flash.message = message(code: 'default.updated.message', args: [message(code: 'customer.label', default: 'Customer'), customerInstance.id])
        redirect(action: "show", id: customerInstance.id)
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def delete() {
        def customerInstance = Customer.get(params.id)
        if (!customerInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'customer.label', default: 'Customer'), params.id])
            redirect(action: "list")
            return
        }

        try {
            customerInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'customer.label', default: 'Customer'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'customer.label', default: 'Customer'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
    
    private Customer setNewCustomer(Customer customer){
        def user = springSecurityService.isLoggedIn() ? User.get(springSecurityService.principal.id) : null
        customer.setUser(user)
        customer.setActive(true)
        customer.setCreated(new Date())
        customer.setLastUpdate(new Date())
        return customer;
    }
}
